package com.hzhr.iot.collect.protocol.processor;

import com.hzhr.iot.collect.Global;
import com.hzhr.iot.collect.constant.MessageFieldKeyEnum;
import com.hzhr.iot.collect.protocol.util.MessageUtil;
import com.hzhr.iot.collect.util.DateUtil;
import com.hzhr.iot.collect.util.StrUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.model.collectData.CollectDataPostModel;
import com.hzhr.iot.device.sdk.model.collectDevice.CollectDeviceModel;
import com.hzhr.iot.device.sdk.model.collectDevice_statusInfo.CollectDevice_StatusInfoPutModel;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDeviceModel;
import com.hzhr.iot.device.sdk.service.Device_CollectDataService;
import com.hzhr.iot.device.sdk.service.Device_CollectDeviceService;
import com.hzhr.iot.device.sdk.service.Device_CollectDevice_StatusInfoService;
import com.hzhr.iot.device.sdk.service.Device_IotDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * DTU 主动上报
 * @author 48310
 *
 */
@Service
public class MessageProcessor36 implements MessageProcessor {
	@Autowired
	Device_CollectDataService device_collectDataService;
	@Autowired
	Device_IotDeviceService device_iotDeviceService;
	@Autowired
	Device_CollectDeviceService device_collectDeviceService;
	@Autowired
	Global global;
	@Autowired
	MessageUtil messageUtil;
	@Autowired
	Device_CollectDevice_StatusInfoService device_collectDevice_statusInfoService;
	
	@Override
	public List<Map<MessageFieldKeyEnum, Object>> proccess(int protocolId, String deviceId, Map<MessageFieldKeyEnum, Object> parsedMessageObj) throws Exception {
		//查询物联网设备
		IotDeviceModel iotDeviceModel = null;
		String iotDeviceCode = HzhrTypeUtil.object2string(parsedMessageObj.get(MessageFieldKeyEnum.IOT_DEVICE_ID));
		if (!StringUtils.isEmpty(iotDeviceCode)) {
			Map<String, String> header = new HashMap<>();
			header.put("token", global.getFirstToken());
			Map<String, Object> query = new HashMap<>();
			query.put("_show", "one");
			query.put("_equal_iotPlatformDeviceId", deviceId);
			iotDeviceModel = device_iotDeviceService.get(header, query).getModel();
		}
		if (iotDeviceModel == null) throw new Exception("物联网设备不存在");

		//查询采集设备
		Map<String, String> header = new HashMap<>();
		header.put("token", global.getFirstToken());
		Map<String, Object> query = new HashMap<>();
		query.put("_show", "one");
		query.put("_show_info", true);
		query.put("_equal_iotDeviceId", iotDeviceModel.getId());
		CollectDeviceModel collectDeviceModel = device_collectDeviceService.get(header, query).getModel();

		Integer cellVoltageInegerPart = HzhrTypeUtil.object2integer(parsedMessageObj.get(MessageFieldKeyEnum.CELL_VOLTAGE_INTEGER_PART));
		Integer cellVoltageDecimalPart = HzhrTypeUtil.object2integer(parsedMessageObj.get(MessageFieldKeyEnum.CELL_VOLTAGE_DECIMAL_PART));
		Float cellVoltage = new BigDecimal(cellVoltageInegerPart + "." + cellVoltageDecimalPart).floatValue();

		Integer signalStrength = HzhrTypeUtil.object2integer(parsedMessageObj.get(MessageFieldKeyEnum.SIGNAL_STRENGTH));

		List<String> currentDateStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.CURRENT_DATE);
		List<String> currentTimeStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.CURRENT_TIME);

		List<String> staTotalFlowIntPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.STANDARD_FLOW_TOTAL_INTEGER_PART);
		List<String> staTotalFlowDecimalPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.STANDARD_FLOW_TOTAL_DECIMAL_PART);

		List<String> workTotalFlowIntPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.WORK_FLOW_TOTAL_INTEGER_PART);
		List<String> workTotalFlowDecimalPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.WORK_FLOW_TOTAL_DECIMAL_PART);

		List<String> staCorrenctionFlowIntPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.STANDARD_CURRECTION_FLOW_INTEGER_PART);
		List<String> staCorrenctionFlowDecimalPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.STANDARD_CURRECTION_FLOW_DECIMAL_PART);

		List<String> staFlowRateIntPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.STANDARD_FLOW_RATE_INTEGER_PART);
		List<String> staFlowRateDecimalPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.STANDARD_FLOW_RATE_DECIMAL_PART);

		List<String> workFlowRateIntPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.WORK_FLOW_RATE_INTEGER_PART);
		List<String> workFlowRateDecimalPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.WORK_FLOW_RATE_DECIMAL_PART);

		List<String> temperatureIntPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.TEMPERATURE_INTEGER_PART);
		List<String> temperatureDecimalPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.TEMPERATURE_DECIMAL_PART);

		List<String> pressureIntPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.PRESSURE_INTEGER_PART);
		List<String> pressureDecimalPartStrList = (List<String>) parsedMessageObj.get(MessageFieldKeyEnum.PRESSURE_DECIMAL_PART);


		if (currentDateStrList != null && currentDateStrList.size() > 0) {
			//写入采集数据
			for (int i = 0; i < currentDateStrList.size(); i++) {
				String currentDateStr = currentDateStrList.get(i);
				String currentTimeStr = currentTimeStrList != null && currentTimeStrList.size() > i ? currentTimeStrList.get(i) : null;

				String staTotalFlowIntPartStr = staTotalFlowIntPartStrList != null && staTotalFlowIntPartStrList.size() > i ? staTotalFlowIntPartStrList.get(i) : null;
				String staTotalFlowDecimalPartStr = staTotalFlowDecimalPartStrList != null && staTotalFlowDecimalPartStrList.size() > i ? staTotalFlowDecimalPartStrList.get(i) : null;

				String workTotalFlowIntPartStr = workTotalFlowIntPartStrList != null && workTotalFlowIntPartStrList.size() > i ? workTotalFlowIntPartStrList.get(i) : null;
				String workTotalFlowDecimalPartStr = workTotalFlowDecimalPartStrList != null && workTotalFlowDecimalPartStrList.size() > i ? workTotalFlowDecimalPartStrList.get(i) : null;

				String staCorrenctionFlowIntPartStr = staCorrenctionFlowIntPartStrList != null && staCorrenctionFlowIntPartStrList.size() > i ? staCorrenctionFlowIntPartStrList.get(i) : null;
				String staCorrenctionFlowDecimalPartStr = staCorrenctionFlowDecimalPartStrList != null && staCorrenctionFlowDecimalPartStrList.size() > i ? staCorrenctionFlowDecimalPartStrList.get(i) : null;

				String staFlowRateIntPartStr = staFlowRateIntPartStrList != null && staFlowRateIntPartStrList.size() > i ? staFlowRateIntPartStrList.get(i) : null;
				String staFlowRateDecimalPartStr = staFlowRateDecimalPartStrList != null && staFlowRateDecimalPartStrList.size() > i ? staFlowRateDecimalPartStrList.get(i) : null;

				String workFlowRateIntPartStr = workFlowRateIntPartStrList != null && workFlowRateIntPartStrList.size() > i ? workFlowRateIntPartStrList.get(i) : null;
				String workFlowRateDecimalPartStr = workFlowRateDecimalPartStrList != null && workFlowRateDecimalPartStrList.size() > i ? workFlowRateDecimalPartStrList.get(i) : null;

				String temperatureIntPartStr = temperatureIntPartStrList != null && temperatureIntPartStrList.size() > i ? temperatureIntPartStrList.get(i) : null;
				String temperatureDecimalPartStr = temperatureDecimalPartStrList != null && temperatureDecimalPartStrList.size() > i ? temperatureDecimalPartStrList.get(i) : null;

				String pressureIntPartStr = pressureIntPartStrList != null && pressureIntPartStrList.size() > i ? pressureIntPartStrList.get(i) : null;
				String pressureDecimalPartStr = pressureDecimalPartStrList != null && pressureDecimalPartStrList.size() > i ? pressureDecimalPartStrList.get(i) : null;

				Date currentTime = DateUtil.strToDate(currentDateStr + currentTimeStr, "yyyyMMddHHmmss");
				CollectDataPostModel postModel = new CollectDataPostModel();
				postModel.setIotDeviceId(iotDeviceModel.getId());
				postModel.setCellVoltage(cellVoltage);
				postModel.setSignalStrength(signalStrength);
				if (collectDeviceModel != null) {
					postModel.setCollectDeviceId(collectDeviceModel.getId());
				}
				postModel.setCurrentTm(currentTime.getTime());

				if (!StringUtils.isEmpty(staTotalFlowIntPartStr)) {
					String staTotalFlowStr = staTotalFlowIntPartStr;
					if (!StringUtils.isEmpty(staTotalFlowDecimalPartStr)) {
						staTotalFlowStr +=  "." + staTotalFlowDecimalPartStr;
					}
					postModel.setCurrentValue(HzhrTypeUtil.object2double(staTotalFlowStr));
					postModel.setStaTotalFlow(HzhrTypeUtil.object2double(staTotalFlowStr));
				}

				if (!StringUtils.isEmpty(workTotalFlowIntPartStr)) {
					String workTotalFlowStr = workTotalFlowIntPartStr;
					if (!StringUtils.isEmpty(workTotalFlowDecimalPartStr)) {
						workTotalFlowStr +=  "." + workTotalFlowDecimalPartStr;
					}
					postModel.setWorkTotalFlow(HzhrTypeUtil.object2double(workTotalFlowStr));
				}

				if (!StringUtils.isEmpty(staCorrenctionFlowIntPartStr)) {
					String staCorrenctionFlowStr = staCorrenctionFlowIntPartStr;
					if (!StringUtils.isEmpty(staCorrenctionFlowDecimalPartStr)) {
						staCorrenctionFlowStr +=  "." + staCorrenctionFlowDecimalPartStr;
					}
					postModel.setDisTotalFlow(HzhrTypeUtil.object2double(staCorrenctionFlowStr));
				}

				if (!StringUtils.isEmpty(staFlowRateIntPartStr)) {
					String staFlowRateStr = staFlowRateIntPartStr;
					if (!StringUtils.isEmpty(staFlowRateDecimalPartStr)) {
						staFlowRateStr +=  "." + staFlowRateDecimalPartStr;
					}
					postModel.setStaFlowRate(HzhrTypeUtil.object2double(staFlowRateStr));
				}

				if (!StringUtils.isEmpty(workFlowRateIntPartStr)) {
					String workFlowRateStr = workFlowRateIntPartStr;
					if (!StringUtils.isEmpty(workFlowRateDecimalPartStr)) {
						workFlowRateStr +=  "." + workFlowRateDecimalPartStr;
					}
					postModel.setWorkFlowRate(HzhrTypeUtil.object2double(workFlowRateStr));
				}

				if (!StringUtils.isEmpty(temperatureIntPartStr)) {
					String temperatureStr = temperatureIntPartStr;
					if (!StringUtils.isEmpty(temperatureDecimalPartStr)) {
						temperatureStr +=  "." + temperatureDecimalPartStr;
					}
					postModel.setTemperature(HzhrTypeUtil.object2float(temperatureStr));
				}

				if (!StringUtils.isEmpty(pressureIntPartStr)) {
					String pressureStr = pressureIntPartStr;
					if (!StringUtils.isEmpty(pressureDecimalPartStr)) {
						pressureStr +=  "." + pressureDecimalPartStr;
					}
					postModel.setPressure(HzhrTypeUtil.object2double(pressureStr));
				}

				query = new HashMap<>();
				device_collectDataService.post(header, query, postModel);
			}

			//更新采集设备的最新状态
			if (collectDeviceModel != null) {
				Integer maxI = null;
				Date maxDate = null;
				for (int i = 0; i < currentDateStrList.size(); i++) {
					String currentDateStr = currentDateStrList.get(i);
					String currentTimeStr = currentTimeStrList != null && currentTimeStrList.size() > i ? currentTimeStrList.get(i) : null;
					Date currentTime = DateUtil.strToDate(currentDateStr + currentTimeStr, "yyyyMMddHHmmss");
					if (maxDate == null || currentTime.getTime() > maxDate.getTime()) {
						maxI = i;
						maxDate = currentTime;
					}
				}
				if(maxI != null) {
					CollectDevice_StatusInfoPutModel collectDevice_statusInfoPutModel = new CollectDevice_StatusInfoPutModel();

					//更新当前读数
					String staTotalFlowIntPartStr = staTotalFlowIntPartStrList != null && staTotalFlowIntPartStrList.size() > maxI ? staTotalFlowIntPartStrList.get(maxI) : null;
					String staTotalFlowDecimalPartStr = staTotalFlowDecimalPartStrList != null && staTotalFlowDecimalPartStrList.size() > maxI ? staTotalFlowDecimalPartStrList.get(maxI) : null;
					if (!StringUtils.isEmpty(staTotalFlowIntPartStr)) {
						String staTotalFlowStr = staTotalFlowIntPartStr;
						if (!StringUtils.isEmpty(staTotalFlowDecimalPartStr)) {
							staTotalFlowStr +=  "." + staTotalFlowDecimalPartStr;
						}
						collectDevice_statusInfoPutModel.setCurrentReading(new BigDecimal(staTotalFlowStr).doubleValue());
					}
					//更新当前电池电压
					collectDevice_statusInfoPutModel.setCurrentCellVoltage(cellVoltage);
					//更新最近采集时间
					collectDevice_statusInfoPutModel.setLastCollectTime(maxDate.getTime());

					header = new HashMap<>();
					header.put("token", global.getFirstToken());
					query = new HashMap<>();
					device_collectDevice_statusInfoService.putByCollectDeviceId(header, collectDeviceModel.getId(), query, collectDevice_statusInfoPutModel);
				}
			}
		}

		List<Map<MessageFieldKeyEnum, Object>> responseMsgList = new ArrayList<>();//响应报文列表
		String dtuNo = StrUtil.removeZeroForLeft(parsedMessageObj.get(MessageFieldKeyEnum.IOT_DEVICE_ID).toString());
		Map<MessageFieldKeyEnum, Object> respMsg = messageUtil.generateDtuResponse(protocolId,
				parsedMessageObj, "0000", dtuNo, parsedMessageObj.get(MessageFieldKeyEnum.SLAVE_STATION_ID).toString(),
				parsedMessageObj.get(MessageFieldKeyEnum.COLLECT_DEVICE_ID).toString());
		responseMsgList.add(respMsg);
		return responseMsgList;
	}
}
